import axios from 'axios'
import { useUserStore } from '@/stores/user'
import { storeToRefs } from 'pinia'
import errorCode from '@/utils/errorCode.js'
import { ElMessage } from 'element-plus'
import router from '@/router'
// 创建axios实例
const service = axios.create({
  baseURL: import.meta.env.VITE_VUE_APP_BASE_API,
  timeout: 8000
})
// 请求拦截
service.interceptors.request.use(
  (config) => {

    const { token } = storeToRefs(useUserStore())
    if (token.value) {
      config.headers.token = token.value;
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 请求响应
service.interceptors.response.use(
  (response) => {
    const userStore = useUserStore()
    const res = response.data,
      code = res.code || 200,
      msg = errorCode[code] || res.message || res['default']
    if (code === 500) {
      ElMessage({
        message: msg || 'Error',
        type: 'error',
        duration: 5000
      })
      return Promise.reject(new Error(msg))
    }

    if (code !== 200) {
      if (code === 401 && userStore.isLogin) {
        // 回到登录
        router.push("/login")
        // 清除用户信息
        userStore.clearUserInfo(router)
        ElMessage({
          message: msg || 'Error',
          type: 'error',
          duration: 5000
        })
      }
      if (code !== 401) {
        ElMessage({
          message: msg || 'Error',
          type: 'error',
          duration: 5000
        })
      }
      return Promise.reject('Error')
    }
    return res
  },
  (error) => {
    // 错误统一处理
    console.log('error', error)
    let { message } = error
    switch (message) {
      case 'Network Error':
        message = '后端接口异常，请稍后重试'
        break
      case message.includes('timeout'):
        message = '请求超时，请稍后重试'
        break
      default:
        message = '系统未知错误，请反馈给管理员'
        break
    }
    ElMessage({
      message,
      type: 'error',
      duration: 5000
    })
    return Promise.reject(error)
  }
)

export default service